package com.voice.call.utils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.voice.call.service.HandlerVosBillService;

public class UDPServerThred extends Thread {
	
	private static final Logger log = LoggerFactory.getLogger(UDPServerThred.class);
	
	HandlerVosBillService handlerVosBillService;
	
	//与云之讯对应的id
	//    ==>主叫uid  caller_uid
	//callercallid ==> 主叫call-id
	//callere164 ==> 主叫 caller
	//calleraccesse164 ==>原始主叫 callernum
	//calleeaccesse164 ==>原始被叫 called
	//starttime ==> start_time
	//stoptime ==> stop_time
	//holdtime ==>通话时长 length
	//endreason ==>挂机原因 reason
	//enddirection ==>挂机原因补充描述 subreason
	// ==>在PAAS平台主叫帐户钱包余额 caller_balance
	
	

	/* * 线程执行的操作，响应客户端的请求 */
	DatagramSocket socket = null; 
	public UDPServerThred(DatagramSocket socket,HandlerVosBillService vService){ 
		this.socket = socket;
		this.handlerVosBillService = vService;
	} 
	public void run(){ 
		//log.info("服务器端接受客户端的数据");
		/* * 服务器端接受客户端的数据 */
		while(true){ 
			byte[] data = new byte[4096];
			DatagramPacket packet = new DatagramPacket(data, data.length); // 指定用于接受数据报的大小
			try {
				//log.info("服务器端开始尝试接收数据");
				socket.receive(packet);// 接受到数据之前该方法处于阻塞状态
				String info = new String(data, 0, packet.getLength());
				
				if(!StringUtil.isEmpty(info)){
					
					
					
					String sendMessage = handlerVosBillService.handlerVosBill(info);
					
					if(sendMessage!=null){
						
						//log.info("replay sendMessage:{}",sendMessage);
						
						/* * 服务器端向客户端进行响应 */
						// 1.定义客户端的地址，端口号，数据
						InetAddress address = packet.getAddress();
						int port = packet.getPort();
						byte[] data2 = sendMessage.getBytes();
						// 2.创建数据报，包含相应信息
						DatagramPacket packet2 = new DatagramPacket(data2, data2.length,address, port);
						// 3.响应客户端
						socket.send(packet2); // 注意这里不能关闭socket，因为在UDPServer类的while是死循环，无法重新创建socket,所以这里不能关闭socket,否则无法进行下一个客户端的监听
						
						//log.info("回复客户端信息完成");
					}
					
					
				}
				
				
				
			} catch (IOException e) {
				e.printStackTrace();
				log.error("udp服务器异常");
			}
		}	
	}
	
	
    
	
	
	
}
